<?php
namespace control;
// 维修记录
class aftermarketRecordClass extends adIndexClass
{
	private const title          = '维修记录';
	private const page           = 'aftermarketRecord';
	private const table          = 'aftermarket';
	private const tableTarget    = 'material';
	private const classify       = ['委外维修', '内部派工'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        $tr = [
            'orderNo'          => [
                'name'  => '单据编号',
                'width' => 200,
                'sort' => 1,
            ],
            'companyName' => [
                'name'  => "客户名称",
                'width' => 150,
            ],
            'name'  => [
                'name'  => "产品名称",
                'width' => 200,
            ],
            'code'  => [
                'name'  => "产品编码",
                'width' => 150,
            ],
            'repairer'  => [
                'name'  => "报修人",
                'width' => 150,
            ],
            'type'         => [
                'name'  => '故障类型',
                'width' => 100,
            ],
            'level'          => [
                'name'  => '故障等级',
                'width' => 200,
                'sort' => 1,
            ],
            'text'          => [
                'name'  => '故障描述',
                'width' => 180,
            ],
            'emergency'          => [
                'name'  => '紧急程度',
                'width' => 180,
            ],
            'classify'          => [
                'name'  => '派工类型',
                'width' => 180,
            ],
            'processors'          => [
                'name'  => '维修人',
                'width' => 180,
            ],
            'commitTime'          => [
                'name'  => '派工时间',
                'width' => 180,
                'sort' => 1,
            ]
        ];
        switch ($fun) {
            case 'aftermarketSearch':
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => "产品名称",
                        'width' => 200,
                    ],
                    'code'  => [
                        'name'  => "产品编码",
                        'width' => 150,
                    ],
                    'repairer'  => [
                        'name'  => "报修人",
                        'width' => 150,
                    ],
                    'type'         => [
                        'name'  => '故障类型',
                        'width' => 100,
                    ],
                    'level'          => [
                        'name'  => '故障等级',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '故障描述',
                        'width' => 180,
                    ],
                    'emergency'          => [
                        'name'  => '紧急程度',
                        'width' => 180,
                    ],
                    'commitTime'          => [
                        'name'  => '派工时间',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'repairFee'          => [
                        'name'  => '维修费用',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'repairDate'          => [
                        'name'  => '维修完成时间',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 180,
                    ]
                ];
                break;
            case 'doneSearch':
                $tr = array_merge($tr,[
                    'repairFee'          => [
                        'name'  => '维修费用',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'repairDate'          => [
                        'name'  => '维修完成时间',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 180,
                    ]
                ]);
                break;
            default:
                $tr = array_merge($tr,[
                    'state'          => [
                        'name'  => '状态',
                        'width' => 180,
                    ]
                ]);
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function aftermarketOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")).
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    "产品名称"   => text(array("name" => "eqName")),
                    "产品编码"   => text(array("name" => "eqCode")),
                ],
                [
                    '故障类型'  => select(["name" => "type", 'option' => explode('，', para('aftermarketType'))]),
                    "故障描述" => select(["name" => "level", 'option' => explode('，', para('aftermarketLevel'))]),
                    '紧急程度' => select(["name" => "emergency", 'option' => explode('，', para('aftermarketEmergency'))]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 客户页卡售后记录
	 *
	 * @return bool|string
	 */
	public function aftermarket(): bool|string
	{
        $html = $this->aftermarketOptions(false);
        $button = "";
        //返回
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
	}

	public function aftermarketSearch(): bool|string
	{
		$khid  = $this->post('targetId');
		$equal = [
			'type'      => $this->post('type'),
			'level'     => $this->post('level'),
			'emergency' => $this->post('emergency'),
			'coid'      => self::$coid,
			'khid'      => $khid,
		];
		$like  = [
			'orderNo'  => $this->post('orderNo'),
			'repairer' => $this->post('repairer'),
			'text'     => $this->post('text'),
		];
		//生成查询语句
		$where = search([
			"="    => $equal,
			"like" => $like,
		]);
		//生成子查询语句
		$targetWhere = search([
			"like" => [
				'code' => $this->post('eqCode'),
				'name' => $this->post('eqName'),
			],
		]);
		if ($targetWhere) {
			$where .= " and targetId IN (SELECT id  FROM `" . self::tableTarget . "` WHERE 1=1 $targetWhere) ";
		}
		// 时间查询
		if ($this->post('repairerTime')) {
			$where .= self::timeComparison($this->post('repairerTime'), 'time', 'repairerTime');
		}
		if ($this->post('commitTime')) {
			$where .= self::timeComparison($this->post('commitTime'), 'time', 'commitTime');
		}
		if ($this->post('repairDate')) {
			$where .= self::timeComparison($this->post('repairDate'), 'time', 'repairDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("markForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate  = [
				"box"    => [
					"name" => "listId", "value" => $array['id'],
				],
				"detail" => [
					"title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')",
				],
			];
			$material  = query(self::tableTarget, " id = '$array[targetId]' ","name,code");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'name':
                    case 'code':
                        $row[] = $material[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='markForm'>" . $li . "</form>" . $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 查询表单
	 *
	 * @param string $state
	 * @return string
	 */
	public function homeForm(string $state): string
	{
		$array = [
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "客户名称"   => clientProfileClass::kehuSelect(array( "title" => '客户名称')),
                    '产品名称' => text(array("name" => "eqName")),
                ],
                [
                    '产品编码' => text(array("name" => "eqCode")),
                    '故障类型'  => select(["name" => "type", 'option' => explode('，', para('aftermarketType'))]),
                    "故障描述" => select(["name" => "level", 'option' => explode('，', para('aftermarketLevel'))]),
                ],
                [
                    '紧急程度' => select(["name" => "emergency", 'option' => explode('，', para('aftermarketEmergency'))]),
                    "派工类型" => select(["name" => "classify", 'option' => self::classify]),
                    "维修单位" => text(['name' => 'processingDepartment']) .
                        hidden(['name' => 'state', 'value' => $state]),
                ]
            ]
        ];
        switch ($state) {
            case '已派工':
                $array[0][] = [
                    '派工时间' => text(['name' => 'commitTime', 'laydate' => ['range' => '~', 'type' => 'datetime']])
                ];
                break;
            case '已完成':
                $array[0][] = [
                    '维修完成时间' => text(['name' => 'repairDate', 'laydate' => ['range' => '~', 'type' => 'datetime']])
                ];
                break;
        }
		return $this->tableShow($array,1);
	}

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已派工');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 查询条件
     *
     * @return string
     */
    public function home(): string
    {
        $html = $this->homeOptions(false);
        $button = "";
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

	/**
	 * 列表页-查询结果
	 *
	 * @return string
	 */
	public function homeSearch(): string
	{
		$state = $this->post('state') ?: '已派工';
		$equal = [
			'type'      => $this->post('type'),
			'level'     => $this->post('level'),
			'emergency' => $this->post('emergency'),
			'state'     => $state,
			'coid'      => self::$coid,
		];
		$like  = [
			'orderNo'  => $this->post('orderNo'),
			'repairer' => $this->post('repairer'),
			'text'     => $this->post('text'),
		];
		//生成查询语句
		$where = search([
			"="    => $equal,
			"like" => $like,
		]);
		//生成子查询语句
		$targetWhere = search([
			"like" => [
				'code' => $this->post('eqCode'),
				'name' => $this->post('eqName'),
			],
		]);
		if ($targetWhere) {
			$where .= " and targetId IN (SELECT id  FROM `" . self::tableTarget . "` WHERE 1=1 $targetWhere) ";
		}
		// 时间查询
		if ($this->post('repairerTime')) {
			$where .= self::timeComparison($this->post('repairerTime'), 'time', 'repairerTime');
		}
		if ($this->post('commitTime')) {
			$where .= self::timeComparison($this->post('commitTime'), 'time', 'commitTime');
		}
		if ($this->post('repairDate')) {
			$where .= self::timeComparison($this->post('repairDate'), 'time', 'repairDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate  = [
				"box"    => [
					"name" => "listId", "value" => $array['id'],
				],
				"detail" => [
					"title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')",
				],
			];
			$material  = query(self::tableTarget, " id = '$array[targetId]' ","name,code");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'companyName':
                        $kehu      = query('kehu', " khid = '$array[khid]'");
                        $row[] = $kehu['companyName'];
                        break;
                    case 'processors':
                        $processors = ($array['classify'] === '内部派工') ? self::findStaff($array['processors']) : $array['processors'];
                        $row[] = $processors;
                        break;
                    case 'name':
                    case 'code':
                        $row[] = $material[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
		return json_encode($json, 320);
	}

    /*列表页-查询条件*/
    public function doneOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已完成');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function done(): string
    {
        $html = $this->doneOptions(false);
        $button = "";
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function doneSearch(): string
    {
        return $this->homeSearch();
    }

	/**
	 * 详情页
	 *
	 * @return string
	 */
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			$material  = query(self::tableTarget, " id = '$info[targetId]' ");
			$kehu      = query('kehu', " khid =  '$info[khid]' ", 'companyName');
			//菜单
			$data   = array(
				"id" => $info['id'],
			);
			$button = [];
			$cla    = 'aftermarketAssign';
			// 显示按钮
			if ($this->power('aftermarketAssign', 'done') && $info['state'] === '已派工') {
				$button[] = [
					"name"  => "填写结果",
					"type"  => "弹出层",
					"cla"   => $cla,
					"fun"   => "operate",
					"post"  => ["act" => 'done', "id" => $info['id'], 'cla' => $this->get('cla')],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($this->power('aftermarketAssign', 'done') && $info['state'] === '已完成') {
				$button[] = [
					"name" => "重新填写结果",
					"type" => "弹出层",
					"cla"  => $cla,
					"fun"  => "operate",
					"post" => ["act" => 'done', "id" => $info['id'], 'cla' => $this->get('cla')],
				];
			}
			//生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html']   = $this->tableShow([
                "基本信息" => [
                    [
                        "客户" => $kehu['companyName'],
                        "产品" => $material['code'] . ' - ' . $material['name'] . ' - ' . ($material['model']?:'无'),
                        "报修人"   => $info['repairer'],
                        "报修时间" => $info['repairerTime'],
                    ],
                    [
                        "故障类型" => $info['type'],
                        "故障等级" => $info['level'],
                        "紧急程度" => $info['emergency'],
                    ],
                    [
                        "故障描述" => pre($info['text']),
                    ],
                    [
                        "故障图片" => fileUploadClass::showImg($info['id'], '故障图片'),
                    ],
                ],
            ]);
			// 进度为派工时
			if (in_array($info['workFlow'], ['派工', '维修'])) {
                $data['html']   .= $this->tableShow([
                    "派工信息" => [
                        [
                            "维修部门" => $info['processingDepartment'],
                            "维修人"   => self::findStaff($info['processors']),
                            "派工时间" => $info['commitTime'],
                        ],
                        [
                            "处理意见" => pre($info['processingResult']),
                        ],
                    ],
                ]);
			}
			// 进度为维修时
			if ($info['workFlow'] == '维修') {
                $data['html']   .= $this->tableShow([
                    "维修记录" => [
                        [
                            "维修日期"      => $info['repairDate'],
                            "维修时长（min）" => $info['repairTime'],
                            "维修结果"      => $info['repairResult'],
                            "维修费用" => $info['repairFee'],
                        ],
                        [
                            "维修措施" => pre($info['repairMeasure']),
                        ],
                    ],
                ]);
				// 关联领用单
				$tr[]   = ['配件编码', '名称', '规格型号', '单位', '数量', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '备注'];
				$result = find([
					'table' => 'parts_inventory as p, parts_inventory_detail as d',
					'field' => 'd.*',
					'where' => " p.id = d.orderId AND p.classify=0 AND  p.state='已确认' AND p.sourceId = '{$info['id']}' ",
				]);
				foreach ($result['array'] as $array) {
					$parts    = query('material', " id = '$array[partsId]' ");
					if (static::isNull($parts['id'])) {
						continue;
					}
					// 减去退货部分
					$returnNum = static::total([
						'sql'   => "SELECT IFNULL(SUM(num), 0) AS total FROM `parts_inventory_detail` ",
						'where' => " `sourceTable` = 'parts_inventory_detail' AND `sourceId` IN (SELECT id FROM `parts_inventory` WHERE classify=0 AND  state='已确认' AND sourceId = '{$info['id']}' ) ",
					]);
					$price     = inventoryBalanceClass::unitPrice($array['partsId']);
					$num       = $array['num'] - $returnNum;
					$money     = round($num * $price, 2);
					$tr[]      = [$parts['code'], $parts['name'], $parts['model'], $parts['unit'], $num, $price, $money, $array['text'],];
				}
                $data['html'] .= $this->detailList([
                    'title' => '配件领用',
                    'html' => $this->listTable(array('tr' => $tr, 'showSort' => true)),
                ]);
			}
            $data['html']   .= $this->tableShow([
                '系统信息' => [
                    [
                        "单据编号" => $info['orderNo'],
                        "创建人"   => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
                    ],
                    [
                        "状态"     => $info['state'],
                    ],
                ],
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

}
